package com.polaris.live.dialog_fragment.room_background.fragment

import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.CollectionUtils
import com.blankj.utilcode.util.StringUtils
import com.lxj.xpopup.XPopup
import com.polaris.live.R
import com.polaris.live.adapter.RoomBackgroundDiyAdapter
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.FragmentRoomBackgroundDiyBinding
import com.polaris.live.dialog.OpenVipDialog
import com.polaris.live.dialog.RoomBackgroundBuyDialog
import com.polaris.live.dialog.RoomBackgroundUpLoadDialog
import com.polaris.live.dialog.VipRenewalTipsDialog
import com.polaris.live.popup.CommodityPopup
import com.polaris.live.resp.back_resp.PayerShopResp
import com.polaris.live.resp.back_resp.UserBackpackConsumableResp
import com.polaris.live.resp.back_resp.UserPartyBackgroundListResp
import com.polaris.live.resp.back_resp.UserPartyBackgroundVo
import com.polaris.live.translation.R.string
import com.polaris.live.utils.CommonUtils.toBoolean
import com.polaris.live.viewmodel.RoomBackgroundViewModel

/**
 * RoomBackgroundDiyFragment
 *
 * @author Created by 半仙 on 2024/12/18/018 17:53
 */
class RoomBackgroundDiyFragment : BaseVbFragment<RoomBackgroundViewModel, FragmentRoomBackgroundDiyBinding>() {

    private val mAdapter by lazy { RoomBackgroundDiyAdapter(mIsPopup) }

    private var mOnClickIndex = 0      //点击的哪个

    //道具
    private val mDecorationList = mutableListOf<UserBackpackConsumableResp>()

    //vip
    private var mUserPartyBackgroundListResp: UserPartyBackgroundListResp? = null

    private val mAnchorId by lazy { arguments?.getLong("anchorId") }

    //是否为派对房里的半弹窗
    private val mIsPopup by lazy { arguments?.getBoolean("isPopup") ?: false }

    override fun initView(savedInstanceState: Bundle?) {
        mBinding.backRecycler.apply {
            adapter = mAdapter
            itemAnimator = null
            layoutManager = GridLayoutManager(context, 3, GridLayoutManager.VERTICAL, false)
        }
        initObserver()
        initListener()
    }

    private fun initListener() {
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            mOnClickIndex = position
            val item = mAdapter.getItemOrNull(mOnClickIndex) ?: return@setOnItemChildClickListener
            when (view.id) {
                //点击封面
                R.id.iv_user_background -> {
                    if (item.activated) {
                        //审核通过  弹窗是点击佩戴或卸下     背包是预览
                        if (item.auditStatus == AppConst.CoverPhoto.APPROVED) {
                            if (mIsPopup) {
                                if (!item.useStatus.toBoolean()) {
                                    mViewModel.usePartyPosition(item.position, AppConst.YES)
                                }

                            } else {
                                //预览回调
                                callbackPreview(item, position)
                            }
                            return@setOnItemChildClickListener
                        }
                        //审核状态不许替换图片佩戴图片
                        if (item.auditStatus == AppConst.CoverPhoto.UNDER_REVIEW) {
                            if (mIsPopup) {
                                ToastGravity.showGravity(string.background_under_review)
                            } else {
                                //预览回调
                                callbackPreview(item, position)
                            }
                            return@setOnItemChildClickListener
                        }
                        //上传背景照
                        upLoadImage(item)
                    } else {
                        ToastGravity.showGravity(string.please_open_this_location)
                    }
                }
                //点击替换
                R.id.tv_delete -> {
                    upLoadImage(item, true)
                }
                //点击底部按钮
                R.id.tv_renewal -> {
                    onClickBottomButton(item)
                }
            }
        }
    }

    //点击续期按钮
    private fun onClickBottomButton(item: UserPartyBackgroundVo) {
        //已激活状态
        if (item.activated) {
            //如果是半弹窗就是续费
            if (mIsPopup) {
                if (item.expireTime != null) { //不是是永久的才能点击
                    //vip槽位就是续费vip
                    if (item.positionType == CommonConst.BackgroundType.VIP) {
                        mUserPartyBackgroundListResp?.vip?.let { vipResp ->
                            VipRenewalTipsDialog.show(requireContext(), vipResp, mViewModel) {
                                //续费成功刷新数据
                                initData()
                                ToastGravity.showGravity(StringUtils.getString(string.buy_success_go_upload_diy_background))
                            }
                        }
                    } else {//不是vip则是判断是否有道具开来续费或购买
                        toolCardBuy(item)
                    }
                }
            } else {
                //审核中不可以使用
                if (item.auditStatus == AppConst.CoverPhoto.UNDER_REVIEW) {
                    ToastGravity.showGravity(string.background_under_review)
                    return
                }
                if (item.background.isNullOrEmpty()) {
                    //上传背景照
                    upLoadImage(item)
                    return
                }

                val useState = if (item.useStatus.toBoolean()) AppConst.NO else AppConst.YES
                mViewModel.usePartyPosition(item.position, useState)
                return
            }
        } else {
            if (item.positionType == CommonConst.BackgroundType.VIP) {
                //没激活展示购买vip弹窗
                OpenVipDialog.show(
                    requireContext(),
                    StringUtils.getString(string.this_vip_position_use, "VIP4")
                )
            } else {
                toolCardBuy(item)
            }
        }
    }

    private fun upLoadImage(item: UserPartyBackgroundVo, isReplace: Boolean = false) {
        //上传背景照
        mUserPartyBackgroundListResp?.maxUploadTimes?.let {
            RoomBackgroundUpLoadDialog.show(
                requireContext(),
                mViewModel,
                it,
                mUserPartyBackgroundListResp?.currentUploadTimes ?: 0,
                item
            ) {
                //是否是替换图片
                if (isReplace) {
                    mOnSelectCallback?.setOnSelectCallback(0, true)
                }
                initData()
            }
        }
    }

    private fun toolCardBuy(item: UserPartyBackgroundVo) {
        //判断是否有道具卡
        if (CollectionUtils.isNotEmpty(mDecorationList)) {
            RoomBackgroundBuyDialog.show(requireContext(), mDecorationList, {
                it?.let { resp ->
                    mViewModel.useConsumable(resp.backpackId, item.position, mAnchorId)
                }
            }, {
                showBuyBackground(item)
            })
        } else {//没有道具卡
            showBuyBackground(item)
        }
    }

    private fun showBuyBackground(item: UserPartyBackgroundVo) {
        val payerShopResp = PayerShopResp(
            item.coins,
            createTime = "",
            displayUrl = "",
            effectDisplayUrl = "",
            expiredTime = item.expireTime.toString(),
            gameCoins = item.gameCoins,
            objectId = item.position.toLong(),
            objectType = CommonConst.DressUp.DIY_BACKGROUND,
            shopDesc = "",
            shopId = item.position.toLong(),
            shopName = StringUtils.getString(string.diy_room_back_position),
            shopType = item.positionType,
            gainCoins = item.gainCoins
        )
        XPopup.Builder(context)
            .moveUpToKeyboard(false)
            .isDestroyOnDismiss(true)
            .hasShadowBg(false)
            .enableDrag(false)
            .asCustom(CommodityPopup(requireActivity(), mViewModel, payerShopResp, true, false, mBuySuccess = {
                //购买成功刷新数据
                initData()
            }))
            .show()
    }

    private fun initObserver() {
        //获取自定义派对背景列表
        mViewModel.mDiyBackgroundLiveData.observe(this) { resultState ->
            mBinding.loadingView.visibility = View.GONE
            parseState(resultState, {
                mAdapter.setList(it.list)
                mUserPartyBackgroundListResp = it
            })
        }
        //获取用户的道具列表
        mViewModel.mDecorationLiveData.observe(this) { resulState ->
            parseState(resulState, {
                mDecorationList.clear()
                it.filter { it.consumableType == CommonConst.PackToolType.BACKGROUND_CARD }
                    .forEach { mDecorationList.add(it) }
            })
        }
        //使用道具
        mViewModel.mConsumableLiveData.observe(this) { resulState ->
            parseState(resulState, {
                initData()
                ToastGravity.showGravity(StringUtils.getString(string.buy_success_go_upload_diy_background))
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }
        //使用自定义位置
        mViewModel.mUsePartyLiveData.observe(this) { resp ->
            //把当前使用的状态修改
            val indexOf = mAdapter.data.indexOfFirst { it.useStatus.toBoolean() }
            if (indexOf != -1) {
                mAdapter.getItemOrNull(indexOf)?.useStatus = AppConst.NOLONG
                mAdapter.notifyItemChanged(indexOf)
            }

            val item = mAdapter.getItemOrNull(mOnClickIndex)
            item?.let {
                it.useStatus = resp.toLong()
                mAdapter.notifyItemChanged(mOnClickIndex)
            }
            //通知背包页取消选中
            mOnSelectCallback?.setOnSelectCallback(0, !resp.toBoolean())

            ToastGravity.showGravity(
                if (resp.toBoolean()) StringUtils.getString(string.room_background_wear_success) else StringUtils.getString(
                    string.uninstall_successfully
                )
            )
        }
    }

    //预览回调
    private fun callbackPreview(item: UserPartyBackgroundVo, position: Int) {
        if (!item.background.isNullOrEmpty()) {
            mOnClickPreviewListener?.invoke(item)
            mAdapter.setSelectPosition(position)
        }
    }

    //在背包页的时候选中预览回调
    private var mOnClickPreviewListener: ((UserPartyBackgroundVo) -> Unit)? = null
    fun setOnClickPreviewListener(l: (UserPartyBackgroundVo) -> Unit) {
        mOnClickPreviewListener = l
    }

    //使用回调，回调到外部告诉有效页取消选中
    private var mOnSelectCallback: OnBackgroundSelectCallback? = null
    fun setOnSelectCallback(l: OnBackgroundSelectCallback) {
        mOnSelectCallback = l
    }

    override fun initData() {
        super.initData()
        mViewModel.getBackgroundDiy()
        mViewModel.getConsumable()
    }

    override fun onResume() {
        super.onResume()
        if (mAdapter.data.isNotEmpty()) {
            initData()
        }
        mAdapter.getSelectData()?.let {
            //预览回调
            callbackPreview(it, mAdapter.getSelectPosition())
        }
    }

    //在半弹窗的时候取消所有选中
    fun setUncheckItem(needUnmount: Boolean) {
        if (!isCreated()) return
        val indexOf = mAdapter.data.indexOfFirst { it.useStatus.toBoolean() }
        val item = mAdapter.getItemOrNull(indexOf) ?: return

        item.useStatus = AppConst.NOLONG
        mAdapter.notifyItemChanged(indexOf)

        if (needUnmount) {
            mViewModel.unMountPartyPosition(item.position)
        }
    }
}